package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.UserNotLoginException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;

import com.sky.utils.HttpClientUtil;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;

@Slf4j
@Service
public class UserServiceImpl implements UserService {


    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatProperties weChatProperties;
    private static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    /**
     * 用户用微信登录小程序
     * @param userLoginDTO
     * @return
     */
    @Override
    public User userLogin(UserLoginDTO userLoginDTO) {
        //调用微信接口得到用户唯一标识openid
        HashMap<String,String> paramMap = new HashMap<>();
        paramMap.put("appid",weChatProperties.getAppid());
        paramMap.put("secret",weChatProperties.getSecret());
        paramMap.put("js_code",userLoginDTO.getCode());
        paramMap.put("grant_type","authorization_code");
        //返回来的数据是json格式
        String respons = HttpClientUtil.doGet(WX_LOGIN, paramMap);
        log.info("http请求响应的数据为:{}",respons);
        JSONObject jsonObject = JSON.parseObject(respons);
        log.info("json格式的数据解析之后的值为:{}",jsonObject);
        log.info("json格式的数据字符串格式为:{}",jsonObject.toString());
        String openid = jsonObject.getString("openid");
        log.info("最终得到的openid为:{}",openid);
        //判断opinid是否为空 为空则抛出异常
        if (respons == null){
           throw new UserNotLoginException(MessageConstant.USER_NOT_LOGIN);
        }
        //不为空则判断是否是新用户
       User user = userMapper.seleteByOpenId(openid);
        if (user == null){
            //是新用户则添加用户id到数据库
          user =  User.builder()
                  .openid(openid)
                  .createTime(LocalDateTime.now())
                  .build();
            userMapper.insert(user);
        }

        return user;
    }

}
